
#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    layoutMainWindow();

//    pageDataManage *dataPage = new pageDataManage;
//    newFunctionPage("  数据管理  ",dataPage);

    system_setting = new System_Setting;
    newFunctionPage("  系统设定  ",system_setting);

    equipment = new Equipment;
    newFunctionPage("  设备检定  ",equipment);

    fhtest = new FhTest;
    newFunctionPage("  负荷测试  ",fhtest);

    bbtest = new BbTest;
    newFunctionPage("  变比测试  ",bbtest);

    cttest = new CtTest;
    newFunctionPage("  误差测试  ",cttest);

//    connect(cttest,SIGNAL(cmdSend()),this,SLOT(sendCmd()));
//    connect(fhtest,SIGNAL(cmdSend()),this,SLOT(sendCmd()));
//    connect(system_setting,SIGNAL(cmdSend()),this,SLOT(sendCmd()));

    //linkToHardware = new serialConnection;

    //connect(linkToHardware->serPort,SIGNAL(readyRead()),this,SLOT(readData()));

}

void MainWindow::layoutMainWindow()
{
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);

    QPalette p = palette();
    p.setColor(QPalette::Window,QColor(200,200,200));
    setPalette(p);

    QFile file(":/image/res/this.css");

    file.open(QFile::ReadOnly);

    QString qss = QLatin1String(file.readAll());

    qApp->setStyleSheet(qss);

    // basic layout of the main window
    QVBoxLayout *layoutMain = new QVBoxLayout;

    // headerBar layout
    QHBoxLayout *layoutHeaderBar = new QHBoxLayout;

    QLabel *labBeforeTitle = new QLabel;
    labBeforeTitle->setFixedSize(100,39);
    labBeforeTitle->setStyleSheet("background:url(:/image/res/icon1.png)  no-repeat center;border:0px;");

    QFont ft;
    ft.setBold(true);
    ft.setPixelSize(25);
    QLabel *labTitle = new QLabel("CT-12"); //仪器名称
    labTitle->setFixedHeight(32);
    labTitle->setFont(ft);
    labTitle->setStyleSheet("color:#666;");

    btnScreenShot = new QPushButton;
    btnScreenShot->setFixedSize(32,32);
    btnScreenShot->setStyleSheet("background:url(:/image/res/icon_screenshot.png)  no-repeat center;border:0px;");
    btnScreenShot->clearFocus();

    QPushButton *btnClose = new QPushButton;
    btnClose->setFixedSize(32,32);
    btnClose->setStyleSheet("background:url(:/image/res/icon_close.png)  no-repeat center;border:0px;");

    btnScreenShot->clearFocus();

    connect(btnClose, SIGNAL(clicked()),this,SLOT(appQuit()));
    connect(btnScreenShot, SIGNAL(clicked()),this,SLOT(takePhoto()));

    layoutHeaderBar->addSpacing(10);
    layoutHeaderBar->addWidget(labBeforeTitle);
    layoutHeaderBar->addWidget(labTitle);
    layoutHeaderBar->addStretch(1);
    layoutHeaderBar->addWidget(btnScreenShot);
    //layoutHeaderBar->addSpacing(5);
    layoutHeaderBar->addWidget(btnClose);
    layoutHeaderBar->addSpacing(10);

    // main area
    QWidget *widgetMainContent = new QWidget;
    widgetMainContent->setFixedSize(1024,555);
    //widgetMainContent->setStyleSheet(".QWidget{background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 white, stop:0.05 #bbb, stop:0.97 #aaa, stop:1 #555);margin:0px;border:0px;border-radius:15px;padding:0px;}");
    //widgetMainContent->setStyleSheet("background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 white, stop:0.02 #ccc, stop:0.98 #bbb, stop:1 #666);");

    // menu bar layout
    QWidget *widgetMenuBar = new QWidget;

    layoutMenuBar = new QHBoxLayout;
    QLabel *blankLabel = new QLabel("");
    blankLabel->setFixedWidth(35);
    blankLabel->setStyleSheet("background:url(:/image/res/click.png)  no-repeat center;border:0px;");
    layoutMenuBar->addWidget(blankLabel);
    layoutMenuBar->addStretch(1);
    layoutMenuBar->setSpacing(10);
    layoutMenuBar->setContentsMargins(15,10,100,8);

    widgetMenuBar->setLayout(layoutMenuBar);
    widgetMenuBar->setFixedHeight(50);
    //widgetMenuBar->setStyleSheet(".QWidget{background-color:qcolor(220,200,20,150);}");
    widgetMenuBar->setStyleSheet(".QWidget{background-color:gray;}");

    ft.setPixelSize(17);
    ft.setBold(false);

    // the stacked widget
    stackedPage = new QStackedWidget;
    stackedPage->setFixedSize(1000,480);
 //   stackedPage->setStyleSheet("background-color:#ffffff");

    listFunctionPage = new QStringList;

    QVBoxLayout *layoutStackedPage = new QVBoxLayout;
    layoutStackedPage->addWidget(widgetMenuBar);
    layoutStackedPage->addSpacing(8);
    layoutStackedPage->addWidget(stackedPage);
    layoutStackedPage->addStretch(1);
    layoutStackedPage->setContentsMargins(0,10,0,0);

    widgetMainContent->setLayout(layoutStackedPage);

    layoutMain->addLayout(layoutHeaderBar);
    layoutMain->addWidget(widgetMainContent);
    layoutMain->addStretch(1);

    // the centralWidget
    QWidget *widgetMain = new QWidget;
    widgetMain->setFixedSize(1024,600);

    // move window to center of sceen
    //QDesktopWidget deskWindow;
    //int deskWidth = deskWindow.width();
    //int deskHeight = deskWindow.height();
    ///this->move(deskWidth / 2 - widgetMain->width() / 2, deskHeight / 2 - widgetMain->height() / 2);
    this->move(0,0);
    widgetMain->setLayout(layoutMain);
    this->setCentralWidget(widgetMain);

    layoutMain->setContentsMargins(0,4,0,4);
}

void MainWindow::newFunctionPage(QString name, QWidget* functionPage)
{    
    addButtonToMenu(name);

    stackedPage->addWidget(functionPage);

    listFunctionPage->append(name);

    switchFunctionPage(name);

//    QFont ft;
//    ft.setPixelSize(20);

//    myButton *btnFunction = new myButton;
//    btnFunction->setText(name);
//    btnFunction->setFont(ft);
//    btnFunction->setMargin(2);

//    layoutMenuBar->insertWidget(1,btnFunction);
//    stackedPage->addWidget(functionPage);

//    listFunctionPage->append(name);

//    switchFunctionPage(name);

//    connect(btnFunction,SIGNAL(clicked(QString)),this,SLOT(switchFunctionPage(QString)));
}

void MainWindow::addButtonToMenu(QString name)
{
    updateMenu(Add, name,0);
}

void MainWindow::toggleButtonInMenu(int pageIndex)
{
    updateMenu(Show, NULL, pageIndex);
}

void MainWindow::updateMenu(menuOperation opt, QString name,int pageIndex)
{
    static QVector <myButton*> listButton;

    if(opt == Add)
    {
        QFont ft;
        ft.setPixelSize(20);

        myButton *btnFunction = new myButton;
        btnFunction->setText(name);
        btnFunction->setFont(ft);
        btnFunction->setMargin(2);

        layoutMenuBar->insertWidget(1,btnFunction);

        listButton.append(btnFunction);

        connect(btnFunction,SIGNAL(clicked(QString)),this,SLOT(switchFunctionPage(QString)));
    }
    else if(opt == Show)
    {
        for(int i = 0; i < listButton.size();i++)
        {
            if(i == pageIndex)
            {
                listButton[i]->highLight(true);
            }
            else
            {
                listButton[i]->highLight(false);
            }
        }
    }
}

void MainWindow::switchFunctionPage(QString name)
{
    int pageIndex = listFunctionPage->indexOf(name);
    stackedPage->setCurrentIndex(pageIndex);

    toggleButtonInMenu(pageIndex);


    btnScreenShot->setFocus();
}

void MainWindow::takePhoto()
{
    QPixmap originalPixmap = QPixmap::grabWindow(QApplication::desktop()->winId());

    QString format = "png";

    QDateTime time = QDateTime::currentDateTime();

    QString str = time.toString("yyyy-MM-dd-hh-mm-ss");

    QString filename = str + ".png";

    QDir toDir= QDir::currentPath();

    if(toDir.exists("screenshot"))
    {
         qDebug() << "/screenshot/ is existed!";

         toDir.setPath("./screenshot");
         toDir.setFilter(QDir::Files);
         toDir.setSorting(QDir::Time);

         QFileInfoList list = toDir.entryInfoList();

         int i = 0;
         for(i=0 ; i<list.size(); i++)
         {
             if(i > 50)
             {
                 QFileInfo fileInfo = list.at(i);
                 toDir.remove( fileInfo.fileName() );

                 qDebug() << "Deleted file: "<<fileInfo.fileName();
             }
         }
    }
    else
    {
         qDebug() << "mkdir screenshot";
         toDir.mkdir("screenshot");
         toDir.setPath("./screenshot");
    }

     filename = toDir.absolutePath()+ "/" + filename;

     if (!filename.isEmpty())
     {
         originalPixmap.save(filename, format.toAscii());
         QString s=tr("截图已保存！请及时使用 U 盘下载！");
//         labInfo->setText(s);
//         widgetInfo->show();
//         showInfoTimer->start(2000);
     }
}

void MainWindow::readData()
{
//    int i=0;
//    static QByteArray rcvBuf;

//    QByteArray cmd;

//    rcvBuf.append(linkToHardware->serPort->readAll());

//    qDebug()<<"new data, in buffer: "<<rcvBuf.toHex();

//find_next_cmd:

//    cmd.resize(0);

//    //as agreed, all data must be readable Character, so using 0xaa and 0xfe as the head and end
//    for(i=0 ; i < rcvBuf.length() ; i++)
//    {
//        if(0xaa == (unsigned char)rcvBuf[i])
//        {
//            rcvBuf = rcvBuf.mid(i);
//            break;
//        }
//    }

//    for(i = 0; i < rcvBuf.length() ; i++)
//    {
//        if(0xfe == (unsigned char)rcvBuf[i])
//        {
//            cmd = rcvBuf.left(i+1);
//            rcvBuf = rcvBuf.mid(i+1);
//            break;
//        }
//    }

//    if((unsigned char)cmd[cmd.length()-1] != 0xfe) return;

//    if((unsigned char)cmd[1] == 0xd1) //transformer error test
//    {
//        cttest->recvResult(cmd);
//    }
//    else if((unsigned char)cmd[1] == 0xd2) //transformer error test
//    {
//        fhtest->recvResult(cmd);
//    }
//    else if((unsigned char)cmd[1] == 0xd3) //transformer error test
//    {
//        system_setting->recvResult(cmd);
//    }

//    if(rcvBuf.length() > 0) goto find_next_cmd;
}

void MainWindow::sendData(QByteArray sendBuf)
{
//    linkToHardware->serPort->write(sendBuf);

//    qDebug()<<"we send: "<<sendBuf.toHex();
}

void MainWindow::sendCmd()
{
//    if(!linkToHardware->serPort->isOpen())
//    {
//        qDebug()<<"main, sendCmd: no connection to hardware!";

//        QWidget* theSender = (QWidget*)sender();

//        if(theSender == cttest)
//        {
//            QByteArray errStr;
//            errStr[0]=0xff;
//            errStr.append(linkToHardware->serPort->errorString());
//            cttest->recvResult(errStr);
//        }
//    }
//    else
//    {
//        QWidget* theSender = (QWidget*)sender();

//        if(theSender == cttest)
//        {
//            qDebug()<<"send"<<cttest->sendBuf.toHex();
//            sendData(cttest->sendBuf);
//        }

//        if(theSender == fhtest)
//        {
//            qDebug()<<"send"<<fhtest->sendBuf.toHex();
//            sendData(fhtest->sendBuf);
//        }

//        if(theSender == system_setting)
//        {
//            qDebug()<<"send"<<system_setting->sendBuf.toHex();
//            sendData(system_setting->sendBuf);
//        }
//    }
}

MainWindow::~MainWindow()
{
    delete fhtest;

    delete system_setting;

    delete cttest;

    delete equipment;

   // delete linkToHardware;
}
